const app = getApp();
import { queryAll, add,getSignDays } from '../../api/sign.js';

Page({
  data: {
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    signData: {
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      currentDay: new Date().getDate(),
      monthTotalDays: 0,
      emptyDays: 0,
      hasSigned: false,
      signedMap: {},
      daysArr: [],   // 日历显示数据
      signDays:0
    }
  },

  onLoad() {
    this.loadData();
    this.getSignDays();
  },

  navBack() {
    wx.switchTab({
      url: '/pages/myDetail/myDetail'
    });
  },

  async loadData() {
    try {
      const res = await queryAll();
      console.log(res);
      if (res.code !== 200 || !Array.isArray(res.data)) {
        wx.showToast({ title: '数据加载异常', icon: 'none' });
        return;
      }

      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1;
      const currentMonthStr = String(currentMonth).padStart(2, '0');
      const currentDay = now.getDate();

      const signedMap = {};
      res.data.forEach(item => {
        const [y, m, d] = item.split('-');
        const month = String(m).padStart(2, '0');
        const day = String(d).padStart(2, '0');
        if (month === currentMonthStr) signedMap[day] = true;
      });

      // 🌟 新增日志：打印已签到的日期（格式：['04', '05', '06']）
      const signedDays = Object.keys(signedMap).sort((a, b) => Number(a) - Number(b));
      console.log(`📅 ${currentYear}年${currentMonth}月已签到日期：`, signedDays);

      const monthTotalDays = new Date(currentYear, currentMonth, 0).getDate();
      const emptyDays = new Date(currentYear, now.getMonth(), 1).getDay();
      const daysArr = [];
      for (let i = 0; i < emptyDays; i++) {
        daysArr.push({ day: '', className: 'empty' });
      }

      for (let d = 1; d <= monthTotalDays; d++) {
        const dayKey = String(d).padStart(2, '0');
        const isSigned = !!signedMap[dayKey];
        const isToday = d === currentDay;
        let className = '';
        if (isSigned) className = 'signed';
        if (isToday) className = 'today';
        daysArr.push({ day: d, className });
      }
      this.setData({
        'signData.signedMap': signedMap,
        'signData.hasSigned': !!signedMap[String(currentDay).padStart(2, '0')],
        'signData.currentYear': currentYear,
        'signData.currentMonth': currentMonth,
        'signData.monthTotalDays': monthTotalDays,
        'signData.emptyDays': emptyDays,
        'signData.daysArr': daysArr,
      });
    } catch (error) {
      wx.showToast({ title: '加载失败，请重试', icon: 'none' });
      console.error('❌ 加载签到数据异常：', error);
    }
  },

  async handleSign() {
    const { hasSigned, currentYear, currentMonth, currentDay, signedMap } = this.data.signData;
    if (hasSigned) {
      wx.showToast({ title: '今日已签到', icon: 'none' });
      return;
    }

    try {
      const signDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(currentDay).padStart(2, '0')} 00:00:00`;
      const res = await add({ date: signDate, status: 1 });

      if (res.code === 200) {
        console.log(res.data);
        wx.showToast({ title: '签到成功', icon: 'success' });
        const dayKey = String(currentDay).padStart(2, '0');
        signedMap[dayKey] = true;
        // 🌟 签到成功后补充日志
        const signedDays = Object.keys(signedMap).sort((a, b) => Number(a) - Number(b));
        console.log(`✅ 签到成功！当前已签到日期：`, signedDays);
        wx.reLaunch({
          url: '/pages/signIn/signIn'
        });
      } else {
        wx.showToast({ title: res.msg || '签到失败', icon: 'none' });
        console.error('❌ 签到接口返回异常：', res);
      }
    } catch (error) {
      wx.showToast({ title: '网络异常', icon: 'none' });
      console.error('❌ 签到网络异常：', error);
    }
  },
  async getSignDays(){
    const res = await getSignDays();
    console.log(res);
    this.setData({
      signDays: res.data
    });
  }
});